<!--
 * @copyright 2025 银杏ERP
 * @author 银杏ERP
 * @version 1.0
 * @license http://www.hhyx.xyz
 * @developer Lhf
-->

<template>
    <el-card shadow="hover" class="warehouse-distribution-card">
        <template #header>
            <div class="card-header">
                <div class="title-with-icon">
                    <Icon name="fa fa-pie-chart" class="title-icon" />
                    <span>{{ t('仓库分布') }}</span>
                </div>
                <div class="header-actions">
                    <el-tooltip :content="t('刷新')" placement="top">
                        <el-button type="primary" link @click="refreshData">
                            <Icon name="fa fa-refresh" />
                        </el-button>
                    </el-tooltip>
                </div>
            </div>
        </template>
        <div v-loading="chartLoading" class="distribution-container">
            <div ref="chartRef" class="chart-container"></div>
            <div class="warehouse-status-list">
                <div class="status-title">{{ t('仓库状态') }}</div>
                <div class="status-grid">
                    <div v-for="(item, index) in warehouseStatus" :key="index" class="status-item">
                        <div class="status-icon" :class="item.statusClass">
                            <Icon :name="item.icon" />
                        </div>
                        <div class="status-info">
                            <div class="status-name">{{ item.name }}</div>
                            <div class="status-count">{{ item.count }}</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import {
    TitleComponent,
    TooltipComponent,
    LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import Icon from '/@/components/icon/index.vue'

// 注册 ECharts 必须的组件
echarts.use([
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    PieChart,
    CanvasRenderer
])

const { t } = useI18n()

const chartRef = ref<HTMLElement | null>(null)
const chartLoading = ref(true)
let chart: echarts.ECharts | null = null

// 仓库分布数据
const warehouseData = ref([
    { name: '总仓', value: 42, percentage: '42%' },
    { name: '北京仓', value: 18, percentage: '18%' },
    { name: '上海仓', value: 16, percentage: '16%' },
    { name: '广州仓', value: 12, percentage: '12%' },
    { name: '成都仓', value: 8, percentage: '8%' },
    { name: '其他', value: 4, percentage: '4%' }
])

// 仓库状态数据
const warehouseStatus = ref([
    { name: t('正常运行'), count: '8', icon: 'fa fa-check-circle', statusClass: 'status-normal' },
    { name: t('接近容量'), count: '3', icon: 'fa fa-exclamation-circle', statusClass: 'status-warning' },
    { name: t('维护中'), count: '1', icon: 'fa fa-wrench', statusClass: 'status-maintenance' },
    { name: t('库存预警'), count: '2', icon: 'fa fa-bell', statusClass: 'status-alert' }
])

// 初始化饼图
const initChart = () => {
    if (!chartRef.value) return
    
    chartLoading.value = true
    
    // 销毁之前的图表实例
    if (chart) {
        chart.dispose()
    }
    
    chart = echarts.init(chartRef.value)
    
    const colors = ['#1E88E5', '#26A69A', '#FFA726', '#EF5350', '#9575CD', '#78909C']
    
    const option = {
        tooltip: {
            trigger: 'item',
            formatter: (params: any) => {
                const { name, value, percent } = params
                return `${name}<br/>${t('库存量')}: ${value}<br/>${t('占比')}: ${percent}%`
            }
        },
        legend: {
            type: 'scroll',
            orient: 'vertical',
            left: 10,
            top: 20,
            bottom: 20,
            textStyle: {
                fontSize: 12
            },
            pageIconSize: 12,
            pageTextStyle: {
                fontSize: 10
            },
            data: warehouseData.value.map(item => item.name),
            formatter: (name: string) => {
                const item = warehouseData.value.find(item => item.name === name)
                if (name.length > 4) {
                    name = name.substring(0, 4) + '..';
                }
                return `${name} (${item?.percentage})`
            }
        },
        series: [
            {
                name: t('仓库分布'),
                type: 'pie',
                radius: ['40%', '70%'],
                center: ['60%', '50%'],
                avoidLabelOverlap: true,
                itemStyle: {
                    borderRadius: 6,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '14',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: warehouseData.value.map((item, index) => ({
                    value: item.value,
                    name: item.name,
                    itemStyle: {
                        color: colors[index % colors.length]
                    }
                }))
            }
        ]
    }
    
    chart.setOption(option)
    chartLoading.value = false
}

// 刷新数据
const refreshData = () => {
    chartLoading.value = true
    
    // 模拟刷新数据过程
    setTimeout(() => {
        // 更新数据 (随机调整数值模拟变化)
        warehouseData.value = warehouseData.value.map(item => {
            // 随机浮动 ±10%
            const adjustment = Math.random() * 0.2 - 0.1
            const newValue = Math.max(1, Math.round(item.value * (1 + adjustment)))
            return { ...item, value: newValue }
        })
        
        // 重新计算百分比
        const total = warehouseData.value.reduce((sum, item) => sum + item.value, 0)
        warehouseData.value = warehouseData.value.map(item => {
            const percentage = Math.round((item.value / total) * 100) + '%'
            return { ...item, percentage }
        })
        
        // 重新初始化图表
        initChart()
    }, 600)
}

// 窗口调整时重绘图表
const handleResize = () => {
    chart?.resize()
}

// 监听窗口大小变化
window.addEventListener('resize', handleResize)

// 组件卸载时移除事件监听
onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    chart?.dispose()
})

// 组件挂载完成后初始化
onMounted(() => {
    nextTick(() => {
        initChart()
    })
})
</script>

<style scoped lang="scss">
.warehouse-distribution-card {
    height: 420px;
    margin-bottom: 20px;
    
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .title-with-icon {
            display: flex;
            align-items: center;
            
            .title-icon {
                color: #FFA726;
                margin-right: 8px;
                font-size: 16px;
            }
        }
        
        .header-actions {
            display: flex;
            align-items: center;
        }
    }
    
    .distribution-container {
        display: flex;
        height: 340px;
        
        .chart-container {
            flex: 1;
            height: 100%;
        }
        
        .warehouse-status-list {
            width: 180px;
            padding-left: 10px;
            
            .status-title {
                font-size: 14px;
                font-weight: bold;
                margin-bottom: 15px;
                color: #606266;
            }
            
            .status-grid {
                display: flex;
                flex-direction: column;
                gap: 15px;
                
                .status-item {
                    display: flex;
                    align-items: center;
                    padding: 10px;
                    border-radius: 8px;
                    background-color: #f8f9fa;
                    transition: all 0.3s;
                    
                    &:hover {
                        transform: translateY(-2px);
                        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
                    }
                    
                    .status-icon {
                        width: 36px;
                        height: 36px;
                        border-radius: 50%;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        margin-right: 10px;
                        
                        &.status-normal {
                            background-color: rgba(38, 166, 154, 0.1);
                            color: #26A69A;
                        }
                        
                        &.status-warning {
                            background-color: rgba(255, 167, 38, 0.1);
                            color: #FFA726;
                        }
                        
                        &.status-maintenance {
                            background-color: rgba(79, 113, 232, 0.1);
                            color: #4F71E8;
                        }
                        
                        &.status-alert {
                            background-color: rgba(239, 83, 80, 0.1);
                            color: #EF5350;
                        }
                    }
                    
                    .status-info {
                        flex: 1;
                        
                        .status-name {
                            font-size: 12px;
                            color: #606266;
                            margin-bottom: 2px;
                        }
                        
                        .status-count {
                            font-weight: bold;
                            font-size: 16px;
                            color: #303133;
                        }
                    }
                }
            }
        }
    }
}

@media screen and (max-width: 1200px) {
    .warehouse-distribution-card {
        .distribution-container {
            flex-direction: column;
            
            .chart-container {
                height: 200px;
            }
            
            .warehouse-status-list {
                width: 100%;
                padding-left: 0;
                padding-top: 15px;
                
                .status-grid {
                    flex-direction: row;
                    flex-wrap: wrap;
                    justify-content: space-between;
                    
                    .status-item {
                        width: calc(50% - 8px);
                    }
                }
            }
        }
    }
}

@media screen and (max-width: 768px) {
    .warehouse-distribution-card {
        height: auto;
        
        .distribution-container {
            height: auto;
            
            .chart-container {
                height: 200px;
            }
        }
    }
}
</style> 